package com.vanzo.tisen.agingtest.activity;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.tisen.agingtest.AgingApplication;
import com.vanzo.tisen.agingtest.R;
import com.vanzo.tisen.agingtest.SharedString;

import java.util.ArrayList;
import java.util.List;

public class AgingTestBegin extends Activity {
    private static int REQUEST_CODE = 0;


    public static final String TAG = "AgingTestBegin";
    private TextView tip;
    private CheckBox mCheckBoxReboot;
    private CheckBox mCheckBoxLcd;
    private CheckBox mCheckBoxSpeaker;
    private CheckBox mCheckBoxVibrator;
    private CheckBox mCheckBoxMic;
    private CheckBox mCheckBoxHandset;
    private CheckBox mCheckBoxCamera;
    private CheckBox mCheckBoxFrontCamera;
    private EditText oneTime;
    private EditText allTime;
    private Button mBegintest;
    private Button mPermission;
    private int duration = 20;
    private int durationAll = 2 * 3600;

    private AgingApplication agingApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.agingtest_begin);
        agingApplication = (AgingApplication) getApplication();
        tip = (TextView) findViewById(R.id.tip_complete);
        mCheckBoxReboot = (CheckBox) findViewById(R.id.checkBoxReboot);
        mCheckBoxLcd = (CheckBox) findViewById(R.id.checkBoxLcd);
        mCheckBoxSpeaker = (CheckBox) findViewById(R.id.checkBoxSpeaker);
        mCheckBoxVibrator = (CheckBox) findViewById(R.id.checkBoxVibrator);
        mCheckBoxHandset = (CheckBox) findViewById(R.id.checkBoxHandset);
        mCheckBoxMic = (CheckBox) findViewById(R.id.checkBoxMic);
        mCheckBoxCamera = (CheckBox) findViewById(R.id.checkBoxCamera);
        mCheckBoxFrontCamera = (CheckBox) findViewById(R.id.checkBoxFrontCamera);
        oneTime = (EditText) findViewById(R.id.one_time_edit);
        allTime = (EditText) findViewById(R.id.all_time_edit);
        mBegintest = (Button) findViewById(R.id.begintest);
        mPermission = (Button) findViewById(R.id.permission);
        mBegintest.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                readToPlay();
            }
        });
        mPermission.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent localIntent = new Intent();
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    localIntent.setAction(Intent.ACTION_VIEW);
                    localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                }
                startActivity(localIntent);
            }
        });
        wakeUpAndUnlock();
        if (agingApplication.getAgingRunning()) {
            if (agingApplication.getDeviceTest(SharedString.IS_REBOOT))
                mCheckBoxReboot.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_LCD))
                mCheckBoxLcd.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_SPEAKER))
                mCheckBoxSpeaker.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_VIBRATOR))
                mCheckBoxVibrator.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_MIC))
                mCheckBoxMic.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_HANDSET))
                mCheckBoxHandset.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_CAMERA))
                mCheckBoxCamera.setChecked(true);
            if (agingApplication.getDeviceTest(SharedString.IS_FRONT_CAMERA))
                mCheckBoxFrontCamera.setChecked(true);
            oneTime.setText(agingApplication.getRoundTime() + "");
            allTime.setText(agingApplication.getAgingTime() + "");
            readToPlay();
        }
    }

    private void wakeUpAndUnlock() {
        // 获取电源管理器对象
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean screenOn = pm.isScreenOn();
        if (!screenOn) {
            // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            PowerManager.WakeLock wl = pm.newWakeLock(
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire(10000); // 点亮屏幕
            wl.release(); // 释放
        }
        // 屏幕解锁
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
        // 屏幕锁定
        keyguardLock.reenableKeyguard();
        keyguardLock.disableKeyguard(); // 解锁
    }

    private void readToPlay() {
        String one_time_edit = oneTime.getText().toString();
        String all_time_edit = allTime.getText().toString();
        try {
            duration = Integer.parseInt(one_time_edit);
            durationAll = Integer.parseInt(all_time_edit);
        } catch (Exception e) {
            Toast.makeText(AgingTestBegin.this, "输入错误", Toast.LENGTH_SHORT).show();
        }

        ArrayList<String> devices = new ArrayList<String>();
        Intent intent = new Intent();
        if (mCheckBoxReboot.isChecked()
                || mCheckBoxLcd.isChecked()
                || mCheckBoxSpeaker.isChecked()
                || mCheckBoxVibrator.isChecked()
                || mCheckBoxMic.isChecked()
                || mCheckBoxHandset.isChecked()
                || mCheckBoxCamera.isChecked()
                || mCheckBoxFrontCamera.isChecked()) {

            if (mCheckBoxReboot.isChecked())
                devices.add("reboot");
            if (mCheckBoxLcd.isChecked())
                devices.add("lcd");
            if (mCheckBoxSpeaker.isChecked())
                devices.add("speaker");
            if (mCheckBoxVibrator.isChecked())
                devices.add("vibrator");
            if (mCheckBoxMic.isChecked())
                devices.add("mic");
            if (mCheckBoxHandset.isChecked())
                devices.add("handset");
            if (mCheckBoxCamera.isChecked())
                devices.add("camera");
            if (mCheckBoxFrontCamera.isChecked())
                devices.add("forntcamera");
            Log.d(TAG, devices.toArray().toString());
            Log.d(TAG, "duration:" + duration);
            Log.d(TAG, "durationAll:" + durationAll);
            agingApplication.setAgingRunning(true);
            intent.putStringArrayListExtra("devices", devices);
            intent.putExtra("duration", duration);
            intent.putExtra("durationAll", durationAll);
            intent.setClass(getApplicationContext(), AgingTesting.class);
            tip.setVisibility(View.GONE);
            startActivityForResult(intent, REQUEST_CODE);
        } else {
            Toast.makeText(AgingTestBegin.this, "至少选择一项", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == AgingTesting.RESULT_CODE && data != null) {
            boolean result = data.getBooleanExtra("result", false);
            if (result) {
                tip.setText("老化测试成功");
            } else {
                tip.setText("老化测试失败");
            }
            tip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        agingApplication.setAgingRunning(false);
        agingApplication.setHasReboot(false);
    }
}
